//
//  NSMutableAttributedString+ZMExtension.swift
//  YHCT
//
//  Created by Rowling on 2021/2/23.
//  Copyright © 2021 智蚂优服. All rights reserved.
//

import UIKit
extension NSMutableAttributedString : ZMCompatible{}
extension ZM where Base : NSMutableAttributedString {
    func append(str : String,font : UIFont? = nil,color : UIColor? = nil, attri : [String : Any]? = nil) -> NSMutableAttributedString {
        let ap = NSMutableAttributedString(string: str)
        var attrs = [NSAttributedString.Key : Any]()
        if let attri = attri {
            // 处理字体
            // 兼容 ["f":"14"],["f":14],["f":UIFont]
            if let f = attri["f"] as? Int {
                attrs[NSAttributedString.Key.font] = UIFont.systemFont(ofSize: CGFloat(f))
            }
            else if let f = attri["f"] as? UIFont {
                attrs[NSAttributedString.Key.font] = f
            }
            else if let f = attri["f"] as? String  {
                if let fInt = Int(f) {
                    attrs[NSAttributedString.Key.font] = UIFont.systemFont(ofSize: CGFloat(fInt))
                }
                if f.zm.match("[0-9]+[M|R|r|m|B|b|s|S]{1}") {
                    var font : UIFont!
                    let num = CGFloat(Int(f.zm.substring(to: f.count-1)) ?? 0)
                    var charactor = f.zm.substring(from: f.count-1)
                    charactor = charactor.lowercased()
                    switch charactor {
                    case "r":
                        font = UIFont.systemFont(ofSize: num, weight: .regular)
                    case "b":
                        font = UIFont.systemFont(ofSize: num, weight: .bold)
                    case "m":
                        font = UIFont.systemFont(ofSize: num, weight: .medium)
                    case "s":
                        font = UIFont.systemFont(ofSize: num, weight: .semibold)
                    default:
                        font = UIFont.systemFont(ofSize: num)
                    }
                    attrs[NSAttributedString.Key.font] = font
                }
            }
            // 处理颜色
            if let c = attri["c"] as? UIColor {
                attrs[NSAttributedString.Key.foregroundColor] = c
            }
            else if let c = attri["c"] as? String {
                attrs[NSAttributedString.Key.foregroundColor] = c.zm.hex()
            }
        }
        
        if let color = color {
             attrs[NSAttributedString.Key.foregroundColor] = color
        }
        if let font = font {
             attrs[NSAttributedString.Key.font] = font
        }
        ap.addAttributes(attrs, range: NSMakeRange(0, ap.length))
        base.append(ap)
        return base
    }
}

